package com.dchh.android.suverynew.act;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.adapter.PhotoGridAdapter;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dchh.android.suverynew.common.ZoomImagePoup;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.bean.ImageInfoBean;
import com.dhcc.android.base.common.view.AlertDialog;
import com.dhcc.android.base.common.view.InputPopupWindow;
import com.dhcc.android.base.common.view.MyLoadingDialog;
import com.dhcc.android.base.db.DBManagerUtil;
import com.dhcc.android.base.db.Sqlite.RecordDBManager;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.FileUtil;
import com.dhcc.android.base.utils.PhotoUtil;
import com.dhcc.android.base.utils.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作物照片拍摄
 *
 * @author zhoudan
 * @date 2016年1月18日
 */
public class ZWPhotoActivity extends SBaseActivity {

    private RelativeLayout main;

    private TextView title;
    private GridView gridView;
    private LinearLayout camera;
    private ToggleButton btn;

    private List<ImageInfoBean> imageInfoList = new ArrayList<ImageInfoBean>();
    private PhotoGridAdapter adapter;
    /**
     * 任务包存储路径
     */
    private String root;
    private String taskName;
    private String dbPath;

    private String tableName = "PHOTO";
    private String beizhu1 = "1作物";
    // private String beizhu2 = "2图纸";

    private boolean tzExist = false; // 图纸是否已经拍摄过照片

    private DBManagerUtil dbManagerUtil;
    private PhotoUtil photoUtil;

    /**
     * 0--作物 3-- 样方图纸
     */
    public static int type; // 0--作物 3-- 样方图纸

    private boolean click = true;
    private String YFBHU;
    private String MYBZ;
    private String yfbh;

    private String dcqb;

    private String namestr = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_zw_grid);
    }


    @Override
    protected void setTitle(TextView toolbar_title) {

    }

    @Override
    protected void initView() {
        root = SPreferencesManager.getValue(MSApplication.TASK_SAVE_PATH, FileUtil.getSavePath());

        taskName = Constants.getTempData(this, MSApplication.TASK);
        dbPath = root + "/" + taskName + "/TASK/TRANSPORT/DATA.db";

        String period = Constants.getTempData(this, MSApplication.PERIOD_LABEL);
        period = period.contains("早稻面积") ? "春播面积" : period;
        dcqb = period + "-" + "遥感面积调查表";

        dbManagerUtil = DBManagerUtil.getInstance(dbPath, this);

        type = getIntent().getIntExtra("type", 0);
        yfbh = getIntent().getStringExtra("yfbh");

        YFBHU = Constants.select.get("YFBHU");

        String cyf = Constants.selects.get(0).get("CUNMC") + "样方" + yfbh;

        String title = "地物拍摄";
        if (type == 3) {
            title = "图纸拍摄";
        }
        title = cyf + title;
        setTitle(title);
        initPhoto();
        initDatas();
        this.title = (TextView) findViewById(R.id.title_textview);
        gridView = (GridView)findViewById(R.id.photo_grid);
        camera = (LinearLayout) findViewById(R.id.opreate_layout);
        btn = (ToggleButton) findViewById(R.id.edit_btn);

        String subtitle = "地物照片(3-10张)";
        if(type == 3){
            subtitle = "图纸照片";
            gridView.setNumColumns(1);
        }

        this.title.setText(subtitle);

        camera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(type == 0){
                    //判断是否超过10张
                    if(imageInfoList.size() < 10){
                        takePhoto();
                    }else{
                        CommenUtil.toast("您已拍满10张照片！", ZWPhotoActivity.this);
                    }
                }else{
                    takePhoto();
                }
            }
        });

        btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                adapter.setDeleteFlag(isChecked);
                adapter.notifyDataSetChanged();
            }
        });


        if(adapter == null){
            adapter = new PhotoGridAdapter(this, imageInfoList);
            adapter.setImageOperate(imgOp);
            gridView.setAdapter(adapter);
        }
        btnEnable();
    }

    PhotoGridAdapter.ImageOperate imgOp = new PhotoGridAdapter.ImageOperate() {

        @Override
        public void OnShow(int position, View view) {
            String path = imageInfoList.get(position).getAbsolutePath();
            if (StringUtil.isNotEmpty(path)) {
                File file = new File(path);
                if (file.exists()) {
                    ZoomImagePoup zp = new ZoomImagePoup(ZWPhotoActivity.this);
                    zp.show(view, path, photoUtil);
                } else {
                    CommenUtil.toast("图片不存在!", ZWPhotoActivity.this);
                }
            } else {
                CommenUtil.toast("图片路径为空!", ZWPhotoActivity.this);
            }
        }

        @Override
        public void OnDelete(int position) {
            String rowid = datas.get(position).get("rowid");
            String name = datas.get(position).get("FILENAME");
            String path = imageInfoList.get(position).getAbsolutePath();

            boolean flag = dbManagerUtil.deleteById(tableName, "rowid", rowid, dbPath);
            if (flag) {
                namestr = namestr.replace(name + ",", "");
                photoUtil.deleteAttachmentFile(path);
                datas.remove(position);
                imageInfoList.remove(position);
                adapter.notifyDataSetChanged();
                if (type == 3) {
                    tzExist = false;
                    adapter.clearMemory();
                }
                btnEnable();
            } else {
                CommenUtil.toast("删除失败", ZWPhotoActivity.this);
            }
        }

    };

    private void btnEnable() {
        btn.setChecked(false);
        if (imageInfoList.size() > 0) {
            btn.setEnabled(true);
        } else {
            btn.setEnabled(false);
        }
    }

    private List<String> keys = new ArrayList<String>();
    private List<Map<String, String>> datas;

    private void initDatas() {
        if (keys.size() == 0) {
//           keys.add("rowid");
            keys.add("FILENAME");
            keys.add("LON");
            keys.add("LAT");
            keys.add("DATE");
            keys.add("村级行政区名称");
            keys.add("样方编号");
            keys.add("自然地块编号");
            keys.add("主要地物");
            keys.add("备注");
            keys.add("DCQB");
            keys.add("TYPE");
        }
        String beizhu = beizhu1;
        if (type == 3) {
            beizhu = myBz;
        }
        String val = YFBHU;
        String bz = MYBZ;
        if (type == 0) {
            datas = dbManagerUtil.getListData(tableName, keys, "样方编号", val, "备注  = '" + beizhu + "' and DCQB = '" + dcqb + "' and TYPE = '" + type + "'", dbPath);
        } else {
            datas = dbManagerUtil.getListData(tableName, keys, "样方编号", val, "DCQB = '" + dcqb + "' and TYPE = '" + type + "'", dbPath);
        }
        imageInfoList.clear();
        if (datas != null && datas.size() > 0) {
            for (Map<String, String> map : datas) {
                namestr += map.get("FILENAME") + ",";
                String photoname = map.get("FILENAME");

                String path = photoUtil.getSavePath(photoname);

                ImageInfoBean im = new ImageInfoBean(photoname.replace(".jpg", ""), path, path);

                imageInfoList.add(im);
            }

            tzExist = true;
        } else {
            tzExist = false;
        }
    }


    //-------------------拍照-------------------------
    private final static int CAMERA_RESULT = 800;

    private void initPhoto() {
        String photopath = root + "/" + taskName + "/SYSTEM/images/zuowu/" + dcqb + "/" + YFBHU;
        if (type == 3) {
            photopath = root + "/" + taskName + "/SYSTEM/images/tuzhi/" + dcqb + "/" + Constants.selects.get(0).get("CUNMC") + "/" + YFBHU;
        }

        photoUtil = new PhotoUtil(this);
        photoUtil.setFilePath(photopath);
    }

    private void takePhoto() {
        String photoName = "";

        photoName = FileUtil.getPhotoFileName(".jpg");
        String path = photoUtil.getSavePath(photoName);
        photoUtil.takePhoto(path);
    }

    /**
     * 拍照返回结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAMERA_RESULT) {
            if (photoUtil.getPhotoSize(photoUtil.mPhotoPath) == 0) {// 文件内容为空
                photoUtil.deleteAttachmentFile(photoUtil.mPhotoPath);
            } else {
                if (type == 0) {
                    doWithGridPhoto();
                } else {
                    doWithCydc();
//                   String imageName = YFBHU + "抽样调查图纸";
//                   savePhoto(imageName);
                }
            }
        }
    }

    /**
     * 保存照片
     */
    private void savePhoto(String imageName, String beizhu) {
        Dialog dialog = MyLoadingDialog.createLoadingDialog(ZWPhotoActivity.this, "正在处理，请稍后...");
        dialog.show();

        String date = photoUtil.getCurrTime("yyyy-MM-dd");
        String location = CommenUtil.getLatLon();// 获取当前地址经纬度
        String lat = "", lon = "";
        if (StringUtil.isNotEmpty(location)) {
            lat = location.split(",")[0];
            lon = location.split(",")[1];
        }
        //处理图片旋转
        int degree = photoUtil.getRotate(photoUtil.mPhotoPath);
        if (degree != 0) {
            photoUtil.rotateBitmap(photoUtil.mPhotoPath, degree);
        }
        String mark = null;
        //处理水印
        if (type == 0) {

            mark = imageName + ",日期：" + date + "," + "样方编号：" + YFBHU;
        } else {
            mark = imageName + ",日期：" + date + "," + "样方编号：" + YFBHU + ",备注：" + beizhu;

        }
        Bitmap bitmap = photoUtil.doPhoto(photoUtil.mPhotoPath, mark);
        if (bitmap != null) {
            if (type == 3 && tzExist) {
                String rowid = datas.get(0).get("rowid");
                dbManagerUtil.deleteById(tableName, "rowid", rowid, dbPath);
            }
            photoUtil.renameFile(photoUtil.mPhotoPath, imageName);

            saveToDB(imageName, lon, lat, date);

            initDatas();
            adapter.setDeleteFlag(false);
            if (type == 3) {
                adapter.clearMemory();
            }
            adapter.notifyDataSetChanged();
            System.out.println("拍照成功--保存到数据库");
            btnEnable();
        } else {
            photoUtil.deleteAttachmentFile(photoUtil.mPhotoPath);
        }

        click = true;
        dialog.dismiss();
    }

    /**
     * 处理后期图片
     *
     * @param bitmap
     */
    String myBz = null;

    private void doWithCydc() {
        InputPopupWindow poup = new InputPopupWindow(this);
        poup.showInputPoupWindow(main, null, "样方位置描述", true, 0, false);
        poup.setClicklistener(new InputPopupWindow.ClickListenerInterface() {

            @Override
            public void doConfirm(String value) {
                if (click) {
                    click = false;
                    myBz = value;
                    String imageName = YFBHU + "抽样调查图纸";
                    savePhoto(imageName, value);
                } else {
                    CommenUtil.toast("正在处理，请稍后...", ZWPhotoActivity.this);
                }
            }

            @Override
            public void doCancel() {
                if (click) {
                    click = false;
                    photoUtil.releaseImage(photoUtil.mPhotoPath);
                    photoUtil.deleteAttachmentFile(photoUtil.mPhotoPath);
                    click = true;
                } else {
                    CommenUtil.toast("正在处理，请稍后...", ZWPhotoActivity.this);
                }
            }

        });

    }

    /**
     * 作物照片拍摄处理
     */
    private void doWithGridPhoto() {
        InputPopupWindow poup = new InputPopupWindow(this);
        poup.showInputPoupWindow(main, null, "地物名称", true, 0, false);
        poup.setClicklistener(new InputPopupWindow.ClickListenerInterface() {

            @Override
            public void doConfirm(String value) {
                if (click) {
                    if (namestr.contains(value + ".jpg,")) {//同名
                        CommenUtil.toast("同名地物照片已存在", ZWPhotoActivity.this);
                        photoUtil.releaseImage(photoUtil.mPhotoPath);
                        photoUtil.deleteAttachmentFile(photoUtil.mPhotoPath);
                    } else {
                        click = false;
                        savePhoto(value, "");
                    }
                } else {
                    CommenUtil.toast("正在处理，请稍后...", ZWPhotoActivity.this);
                }
            }

            @Override
            public void doCancel() {
                if (click) {
                    click = false;
                    photoUtil.releaseImage(photoUtil.mPhotoPath);
                    photoUtil.deleteAttachmentFile(photoUtil.mPhotoPath);
                    click = true;
                } else {
                    CommenUtil.toast("正在处理，请稍后...", ZWPhotoActivity.this);
                }
            }

        });

    }

    /**
     * 保存到数据库
     */
    public void saveToDB(String value, String lon, String lat, String date) {
        String beizhu = beizhu1;
        if (type == 3) {
            beizhu = myBz;
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("PHOTOID", Constants.selects.get(0).get("CUNDM") + "_" + photoUtil.getCurrTime(null));
        map.put("FILENAME", value + ".jpg");
        map.put("LON", lon);
        map.put("LAT", lat);
        map.put("DATE", date);
        map.put("村级行政区名称", Constants.selects.get(0).get("CUNMC"));
        map.put("样方编号", YFBHU);
        map.put("自然地块编号", "");
        map.put("主要地物", "");
        map.put("备注", beizhu);
        map.put("DCQB", dcqb);
        map.put("TYPE", String.valueOf(type));

        dbManagerUtil.add(map, keys, tableName, "", dbPath);

        if (type == 3) {
            //保存进度记录
            RecordDBManager rcdDB = new RecordDBManager(ZWPhotoActivity.this);
            rcdDB.add(YFBHU, Constants.selects.get(0).get("CUNDM"), "2", "002");
        }

    }
    //-------------------拍照【完】--------------------


    private void isAlertDialog(final Activity activity, String str, String right, String left) {
        final AlertDialog alertDialog = new AlertDialog(activity, str, right, left);
        alertDialog.show();
        alertDialog.setClicklistener(new AlertDialog.ClickListenerInterface() {

            @Override
            public void doConfirm() {
                alertDialog.dismiss();
                ZWPhotoActivity.this.finish();
                ZWPhotoActivity.this.overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
            }

            @Override
            public void doCancel() {
                alertDialog.dismiss();
            }
        });
    }

}
